package datebase.live.access;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.trackvoodoo.models.NewsItemDocument.NewsItem;
import com.trackvoodoo.models.NewsListDocument.NewsList;

import database.connector.DatabaseFactory;
import database.live.DOAStatements;
import database.live.MySqlDAO;
import engine.EngineUtils;

public class NewsDAO {

	private NewsDAO(){};
	
	public static NewsList getLatestItems(int count)
	{
		return getNewsItems(0,count);
	}
	
	public static NewsList getNewsItems(int startPos, int endPos)  // 0 is the start remeber.!
	{
		MySqlDAO d = (MySqlDAO) DatabaseFactory.getDAO();
		NewsList nList = NewsList.Factory.newInstance();
		try{
			
			
			PreparedStatement p = d.getPreparedStatement(DOAStatements.SELECT_NEWS); //idnewsItem, dateCreated, header, story, picture
			p.setInt(1, startPos);
			p.setInt(2, endPos);
			ResultSet rs = p.executeQuery();
			
			while (rs.next())
			{
				NewsItem item = nList.addNewNewsItem();
				item.setId(rs.getInt(1));
				item.setDate(EngineUtils.dateToCalendar(rs.getDate(2)));
				item.setTitle(rs.getString(3));
				item.setItem(rs.getString(4));
				item.setPicture(rs.getString(5));
			}
		}
		catch (SQLException s)
		{
			System.out.println(s.getMessage());
			return null;
		}
		finally
		{
			d.closeConnection();
		}
		return nList;
	}
	
	
}
